package py.com.alfa.escriba.gui.spring.processors;

import java.lang.reflect.Field;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;

import py.com.alfa.escriba.gui.config.EscribaGUIApplicationContextProvider;



public class SpringBeanPostProcessor implements BeanPostProcessor {
 
    public Object postProcessAfterInitialization(Object bean, String beanName) throws
        BeansException {
        return bean;
    }
 
    public Object postProcessBeforeInitialization(final Object bean, String beanName)
          throws BeansException {
       
    	ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
			
			public void doWith(Field field) throws IllegalArgumentException,
					IllegalAccessException {
				ReflectionUtils.makeAccessible(field);

				// Check if the field is annoted with @ControllerObject
				if (field.getAnnotation(SpringBean.class) != null) {
					ApplicationContext ctx = EscribaGUIApplicationContextProvider.getContext();
					SpringBean restServicetAnnotation = field.getAnnotation(SpringBean.class);
					String beanName = restServicetAnnotation.value();
					if(beanName.trim().isEmpty()){
						beanName = field.getName();
					}
					Object instance  = ctx.getBean(beanName);
					field.set(bean, instance);
				}
			}
		});
 
        return bean;
    }
}
